package com.zb.emq;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.zb.entity.TbQuotaModel;
import com.zb.service.TbQuotaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Random;

@Component
@EnableScheduling //开启定时任务
public class Mock {
    @Autowired
    private TbQuotaService quotaService;
    @Autowired
    private EmqClient emqClient;

    @Scheduled(cron = "0/30 * * * * ?")
    public void addData(){
        System.out.println("定时生成数据。。。");
        List<TbQuotaModel> list = quotaService.list();
        for (int i = 0; i <= 10; i++) {
            String deviceId = null;
            if (i>=10){
                deviceId = "10"+i;
            }else {
                deviceId = "100"+i;
            }
            for (TbQuotaModel quotaModel : list) {
                HashMap<String, Object> map = Maps.newHashMap();
                map.put(quotaModel.getSnKey(),deviceId);
                Random random = new Random();
                int quotaValue = random.nextInt(100);
                map.put(quotaModel.getValueKey(),quotaValue);
                String json = JSON.toJSONString(map);
                System.out.println(json);
                emqClient.publish(quotaModel.getSubject(),json);
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
